package com.orange.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Formatter;
import java.util.Locale;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.ParcelFileDescriptor;

import com.orange.lswidget.R;
import com.orange.lswidget.widgets.musicplayer.entry.MusicPlayer;
import com.orange.notificationsummary.utils.Constants;

public class MusicUtils {
	private static final String	TAG					= "MusicPlayerAppWidget";

	private static final int	EXTRACT_MAX_HEIGHT	= 108;
	private static final int	EXTRACT_MAX_WIDTH	= 108;
	private static final Uri	ARTWORK_URI			= Uri.parse("content://media/external/audio/albumart");

	/**
	 * Get album art for specified album. You should not pass in the album id
	 * for the "unknown" album here (use -1 instead)
	 */
	public static Bitmap getArtwork(Context context, long album_id) {
		LogHelper.d(TAG, "getArtwork. album_id = " + album_id);

		if (album_id < 0) {
			LogHelper.w(TAG, "getArtwork. Return default. [album_id < 0");
			return getDefaultArtwork(context);
		}

		ContentResolver res = context.getContentResolver();
		Uri uri = ContentUris.withAppendedId(ARTWORK_URI, album_id);
		LogHelper.i(TAG, "getArtwork. Uri:" + uri);

		if (uri != null) {
			ParcelFileDescriptor fd = null;
			try {
				// in = res.openInputStream(uri);
				fd = res.openFileDescriptor(uri, "r");
				int sampleSize = 1;

				BitmapFactory.Options opts = new BitmapFactory.Options();
				opts.inJustDecodeBounds = true;
				BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(),
						null, opts);
				LogHelper.d(TAG, "getArtwork. [outWidth=" + opts.outWidth
						+ ", outHeight=" + opts.outHeight);

				// http://www.cnblogs.com/RayLee/archive/2010/11/09/1872856.html
				int nextWidth = opts.outWidth;
				int nextHeight = opts.outHeight;
				while (nextWidth > EXTRACT_MAX_WIDTH
						&& nextHeight > EXTRACT_MAX_HEIGHT) {
					sampleSize <<= 1;
					nextWidth >>= 1;
					nextHeight >>= 1;
				}

				opts.inSampleSize = sampleSize;
				opts.inJustDecodeBounds = false;
				Bitmap b = BitmapFactory.decodeFileDescriptor(
						fd.getFileDescriptor(), null, opts);

				LogHelper.d(TAG,
						"getArtwork. [nextWidth=" + nextWidth + ", nextHeight="
								+ nextHeight + ", sampleSize=" + sampleSize
								+ ", b=" + b + ", bitmap width=" + b.getWidth()
								+ ", height=" + b.getHeight());
				return b;
			} catch (Exception ex) {
				return getDefaultArtwork(context);
			} finally {
				try {
					if (fd != null) {
						fd.close();
					}
				} catch (IOException ex) {
				}
			}
		}

		return getDefaultArtwork(context);
	}

	private static Bitmap getDefaultArtwork(Context context) {
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inPreferredConfig = Bitmap.Config.RGB_565;
		// opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
		return BitmapFactory
				.decodeStream(
						context.getResources().openRawResource(
								R.drawable.music_albumart_unknown), null, opts);
	}

	public static byte[] getByteFromFile(String path) {
		byte[] data = null;
		Bitmap bitmap = BitmapFactory.decodeFile(path);
		if (bitmap != null) {
			final ByteArrayOutputStream os = new ByteArrayOutputStream();
			if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os)) {
				data = os.toByteArray();
				try {
					os.close();
				} catch (IOException e1) {
				}
			}
		}

		return data;
	}

	public static int getShowMusicSetting(Context context) {
		Context otherAppContext = null;
		String showMode = "0";

		try {
			otherAppContext = context.createPackageContext(
					Constants.PKG_LOCKSCREEN_SETTING,
					Context.CONTEXT_IGNORE_SECURITY);
			if (null != otherAppContext) {
				SharedPreferences sp = otherAppContext.getSharedPreferences(
						Constants.PREFERENCES_SETTINGS_NAME,
						Context.MODE_WORLD_READABLE);
				showMode = sp.getString("preference_widget_music", "0");
			}
		} catch (NameNotFoundException e) {
		}

		return Integer.valueOf(showMode);
	}

	public static int updateMusicTrackSelected(Context context, String value) {
		LogHelper.v(TAG, "updateMusicTrackSelected. value: " + value);
		ContentResolver resolver = context.getContentResolver();
		ContentValues values = new ContentValues();
		int ret = 0;

		values.put(MusicPlayer.COLUMN_MUSIC_TRACK_SELECTED, value);
		String where = MusicPlayer._ID + " = 1";
		ret = resolver.update(MusicPlayer.CONTENT_URI, values, where, null);

		LogHelper.d(TAG, "updateMusicTrackSelected. ret: " + ret);
		return ret;
	}

	public static boolean isMusicTrackSelected(Context context) {
		ContentResolver resolver = context.getContentResolver();
		String[] projection = new String[] { MusicPlayer.COLUMN_MUSIC_TRACK_SELECTED };
		Cursor cursor = null;
		try {
			cursor = resolver.query(MusicPlayer.CONTENT_URI, projection, null,
					null, null);
			if (cursor != null && cursor.getCount() > 0) {
				cursor.moveToNext();
				int selectIndex = cursor
						.getColumnIndex(MusicPlayer.COLUMN_MUSIC_TRACK_SELECTED);
				String isSelected = cursor.getString(selectIndex);
				// return isSelected.equals("true") ? true : false;
				return "true".equals(isSelected) ? true : false;
			}
		} catch (Exception e) {
			LogHelper.e(TAG, "isMusicTrackSelected. ", e);
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}

		return false;
	}

	public static boolean isPackageExist(Context context, String packageName) {
		try {
			context.getPackageManager().getPackageInfo(packageName,
					PackageManager.GET_SERVICES);
		} catch (NameNotFoundException e) {
			return false;
		}

		return true;
	}

	public static Cursor query(Context context, Uri uri, String[] projection,
			String selection, String[] selectionArgs, String sortOrder) {
		return query(context, uri, projection, selection, selectionArgs,
				sortOrder, 0);
	}

	public static Cursor query(Context context, Uri uri, String[] projection,
			String selection, String[] selectionArgs, String sortOrder,
			int limit) {
		Uri tempUri = uri;
		try {
			ContentResolver resolver = context.getContentResolver();
			if (resolver == null) {
				return null;
			}
			if (limit > 0) {
				tempUri = tempUri.buildUpon()
						.appendQueryParameter("limit", Integer.toString(limit))
						.build();
			}
			return resolver.query(tempUri, projection, selection,
					selectionArgs, sortOrder);
		} catch (UnsupportedOperationException ex) {
			LogHelper.e(TAG, "query. ", ex);
			return null;
		}

	}

	private static StringBuilder	sFormatBuilder	= new StringBuilder();
	private static Formatter		sFormatter		= new Formatter(
															sFormatBuilder,
															Locale.getDefault());
	private static final Object[]	sTimeArgs		= new Object[5];

	public static String makeTimeString(Context context, long secs) {
		String durationformat = context
				.getString(secs < 3600 ? R.string.durationformatshort : R.string.durationformatlong);

		/*
		 * Provide multiple arguments so the format can be changed easily by
		 * modifying the xml.
		 */
		sFormatBuilder.setLength(0);

		final Object[] timeArgs = sTimeArgs;
		timeArgs[0] = secs / 3600;
		timeArgs[1] = secs / 60;
		timeArgs[2] = (secs / 60) % 60;
		timeArgs[3] = secs;
		timeArgs[4] = secs % 60;

		return sFormatter.format(durationformat, timeArgs).toString();
	}
}
